package cn.cmcc.online.smsapi.sdk.db.entity;

import java.util.List;

import android.content.ContentValues;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.XyCursor;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;

public class ResdownloadManager {

    public static final int NOTFINISH = 0;
    public static final int FINISH = 1;

    public static final String ID = "id";
    public static final String SCENE_ID = "scene_id";
    public static final String URL = "url";
    public static final String STATUS = "status";// 0未下载(包括还没下载完的)，1下载完毕
    public static final String POS = "pos";
    public static final String LASTLOADTIME = "last_load_time";
    public static final String TABLE_NAME = "tb_res_download";

    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;
    public static final String CREATE_TABLE = "create table  if not exists " + TABLE_NAME + " (" + ID
            + " INTEGER PRIMARY KEY," + SCENE_ID + " TEXT," + URL + " TEXT," + STATUS + " INTEGER," + POS + " INTEGER,"
            + LASTLOADTIME + " INTEGER DEFAULT '0' " + ")";

    public static final String ADD_LASTLOADTIME = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + LASTLOADTIME
            + " INTEGER DEFAULT '0'";

    // public static List<String> loadList = new ArrayList<String>();
    // public static boolean isLoad = false;

    public static void addResdownload(Resdownload resdownload) {

        try {
            ContentValues values = setValues(resdownload);
            DBManager.insert(TABLE_NAME, values);

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "addResdownload error", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {

        }

    }

    public static ContentValues setValues(Resdownload resdownload) {
        ContentValues values = new ContentValues();
        values.put(SCENE_ID, resdownload.scene_id);
        values.put(URL, resdownload.url);
        values.put(STATUS, resdownload.status);
        values.put(POS, resdownload.pos);
        values.put(LASTLOADTIME, 0);
        return values;
    }

    public static List<String> getUrls(String urls) {
        try {
            if (!StringUtils.isNull(urls)) {
                String str[] = urls.split(";");
                List list = java.util.Arrays.asList(str);
                return list;
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "getUrls error ", e);
            /* SDK-550 hewengao 20160719 end */
        }
        return null;
    }

    /*
     * public static List<Resdownload> getNeedDownload(String urls){
     * List<Resdownload> Resdownloadlist = new ArrayList<Resdownload>();
     * XyCursor xyCursor=null; try { String str[] = urls.split(";"); List list =
     * java.util.Arrays.asList(str); if(list!=null&&!list.isEmpty()) { int size
     * = list.size(); for(int i=0;i<size;i++) { String url =
     * (String)list.get(i); xyCursor=DBManager.query(TABLE_NAME, new
     * String[]{ID,SCENE_ID,URL,STATUS,POS}, URL+"=? ", new String[]{url});
     * if(xyCursor!=null&&xyCursor.getCount()>0 ){ int
     * idIndex=xyCursor.getColumnIndex(ID); int
     * scenceIndex=xyCursor.getColumnIndex(SCENE_ID); int
     * statusIndex=xyCursor.getColumnIndex(STATUS); int
     * posIndex=xyCursor.getColumnIndex(POS); while(xyCursor.moveToNext()) {
     * long id =xyCursor.getLong(idIndex); String scenceId =
     * xyCursor.getString(scenceIndex); int status =
     * xyCursor.getInt(statusIndex); int pos = xyCursor.getInt(posIndex);
     * Resdownload resdownload = new Resdownload(); resdownload.id =id;
     * resdownload.scene_id =scenceId; resdownload.status=status;
     * resdownload.pos=pos; resdownload.url=url;
     * Resdownloadlist.add(resdownload);
     * 
     * } } } } } catch (Throwable e) { // TODO: handle Throwable }finally{ if
     * (xyCursor != null) { xyCursor.close(); xyCursor = null; } } return
     * Resdownloadlist;
     * 
     * }
     */

    public static boolean isResDownloaded(String url) {
        if (StringUtils.isNull(url))
            return false;
        XyCursor cur = null;
        try {
            cur = DBManager.query(TABLE_NAME, new String[] { ID, URL, STATUS }, URL + " = ? and " + STATUS + " = ?",
                    new String[] { url + "", FINISH + "" });
            if (cur != null && cur.getCount() > 0) {
                return true;
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.e(Constant.TAG, "isResDownloaded: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return false;

    }

    public static Resdownload insertOrUpdate(Resdownload resdownload) {
        long result = -1;
        XyCursor xyCursor = null;
        try {
            xyCursor = DBManager.query(TABLE_NAME, new String[] { ID, SCENE_ID, URL, STATUS, POS }, URL + " = ? ",
                    new String[] { resdownload.url });
            if (xyCursor != null && xyCursor.getCount() > 0) {
                int idIndex = xyCursor.getColumnIndex(ID);
                int scenceIndex = xyCursor.getColumnIndex(SCENE_ID);
                int statusIndex = xyCursor.getColumnIndex(STATUS);
                int posIndex = xyCursor.getColumnIndex(POS);
                while (xyCursor.moveToNext()) {
                    long id = xyCursor.getLong(idIndex);
                    String scenceId = xyCursor.getString(scenceIndex);
                    int status = xyCursor.getInt(statusIndex);
                    int pos = xyCursor.getInt(posIndex);
                    resdownload.id = id;
                    resdownload.scene_id = scenceId;
                    resdownload.status = status;
                    resdownload.pos = pos;
                    return resdownload;

                }
            } else {
                ContentValues values = setValues(resdownload);
                result = DBManager.insert(TABLE_NAME, values);
                if (result > -1) {
                    resdownload.id = result;
                    return resdownload;
                }
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.e(Constant.TAG, "insertOrUpdate: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }
        return resdownload;
    }

    public static void updateResdownloadStatus(long id, int status, String url) {
        try {
            ContentValues values = new ContentValues();
            values.put(STATUS, status);
            DBManager.update(TABLE_NAME, values, ID + " = ? ", new String[] { id + "" });

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "updateResdownloadStatus error: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {

        }
    }

    public static void deleteAll() {
        try {
            DBManager.delete(TABLE_NAME, null, null);

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "deleteAll: ", e);
            /* SDK-550 hewengao 20160719 end */
        }
    }

    private static void updateLoadTime(Resdownload resdownload) {

        try {

            ContentValues values = new ContentValues();
            values.put(LASTLOADTIME, System.currentTimeMillis() + "");
            DBManager.update(TABLE_NAME, values, ID + " = ? ", new String[] { resdownload.id + "" });

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.e(Constant.TAG, "updateLoadTime error: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {

        }

    }

    public static void updateLoadTime(Resdownload resdownload, long time) {

        try {

            ContentValues values = new ContentValues();
            values.put(LASTLOADTIME, time + "");
            DBManager.update(TABLE_NAME, values, ID + " = ? ", new String[] { resdownload.id + "" });

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.e(Constant.TAG, "updateLoadTime: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {

        }

    }

    // 获取1个还没下载完的Resdownload
    public static Resdownload getOneNotFinishDownload() {
        XyCursor xyCursor = null;
        try {

            xyCursor = DBManager.query(TABLE_NAME, new String[] { ID, SCENE_ID, URL, STATUS, POS }, STATUS
                    + "= ? and last_load_time < ?", new String[] { NOTFINISH + "",
                    System.currentTimeMillis() - 3600 * 6 * 1000 + "" }, null, null, "id asc", "1");
            if (xyCursor != null && xyCursor.getCount() > 0) {
                int idIndex = xyCursor.getColumnIndex(ID);
                int scenceIndex = xyCursor.getColumnIndex(SCENE_ID);
                int statusIndex = xyCursor.getColumnIndex(STATUS);
                int posIndex = xyCursor.getColumnIndex(POS);
                int urlIndex = xyCursor.getColumnIndex(URL);
                while (xyCursor.moveToNext()) {
                    long id = xyCursor.getLong(idIndex);
                    String scenceId = xyCursor.getString(scenceIndex);
                    int status = xyCursor.getInt(statusIndex);
                    int pos = xyCursor.getInt(posIndex);
                    String url = xyCursor.getString(urlIndex);
                    Resdownload resdownload = new Resdownload();
                    resdownload.id = id;
                    resdownload.scene_id = scenceId;
                    resdownload.status = status;
                    resdownload.pos = pos;
                    resdownload.url = url;
                    updateLoadTime(resdownload);
                    return resdownload;

                }
            }

        } catch (Throwable e) {
            // TODO: handle Throwable
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }
        return null;

    }

    // 获取1个还没下载完的Resdownload
    public static Resdownload getNeedPriorDownUrlData(String url) {
        XyCursor xyCursor = null;
        try {

            xyCursor = DBManager.query(TABLE_NAME, new String[] { ID, SCENE_ID, URL, STATUS, POS }, STATUS
                    + "= ? and url =? ", new String[] { NOTFINISH + "", url }, null, null, "id asc", "1");
            if (xyCursor != null && xyCursor.getCount() > 0) {
                int idIndex = xyCursor.getColumnIndex(ID);
                int scenceIndex = xyCursor.getColumnIndex(SCENE_ID);
                int statusIndex = xyCursor.getColumnIndex(STATUS);
                int posIndex = xyCursor.getColumnIndex(POS);
                int urlIndex = xyCursor.getColumnIndex(URL);
                while (xyCursor.moveToNext()) {
                    long id = xyCursor.getLong(idIndex);
                    String scenceId = xyCursor.getString(scenceIndex);
                    int status = xyCursor.getInt(statusIndex);
                    int pos = xyCursor.getInt(posIndex);
                    url = xyCursor.getString(urlIndex);
                    Resdownload resdownload = new Resdownload();
                    resdownload.id = id;
                    resdownload.scene_id = scenceId;
                    resdownload.status = status;
                    resdownload.pos = pos;
                    resdownload.url = url;
                    updateLoadTime(resdownload);
                    return resdownload;

                }
            }

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "getNeedPriorDownUrlData: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }
        return null;

    }
	
	/*public static List<Resdownload> getAllLoadResdownload(){
		List<Resdownload> Resdownloadlist = new ArrayList<Resdownload>();
		XyCursor xyCursor=null;
		try {
			xyCursor=DBManager.query(TABLE_NAME, new String[]{ID,SCENE_ID,URL,STATUS,POS},
					STATUS +" = ?" ,new String[]{FINISH+""});
			if(xyCursor!=null&&xyCursor.getCount()>0 ){
				int idIndex=xyCursor.getColumnIndex(ID);
				int scenceIndex=xyCursor.getColumnIndex(SCENE_ID);						
				int statusIndex=xyCursor.getColumnIndex(STATUS);
				int posIndex=xyCursor.getColumnIndex(POS);
				int urlIndex=xyCursor.getColumnIndex(URL);
				while(xyCursor.moveToNext())
				{
					long id =xyCursor.getLong(idIndex);
					String scenceId = xyCursor.getString(scenceIndex);
					String url = xyCursor.getString(urlIndex);
					int  status = xyCursor.getInt(statusIndex);
					int pos = xyCursor.getInt(posIndex);
					Resdownload resdownload = new Resdownload();
					resdownload.id =id;
					resdownload.scene_id =scenceId;
					resdownload.status=status;
					resdownload.pos=pos;
					resdownload.url=url;
					Resdownloadlist.add(resdownload);
					
				}			
			}
		
		} catch (Throwable e) {
			// TODO: handle exception
		}finally{
			 if (xyCursor != null) {
	                xyCursor.close(true);
	                xyCursor = null;
	            }
		}
		return Resdownloadlist;
		
	}*/
}
